// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.lang;

import java.io.IOException;
import java.io.InputStream;

public abstract class IOUtils {
	
	public static int READ_LIMIT_1K = 1024;
	public static int READ_LIMIT_4K = 4096;

	/**
	 * Convert a stream to a string and reset stream to last postion.
	 * @param input a stream supporting 'mark' feature
	 * @return stream as a string or null if stream is null. 
	 * @throws IllegalArgumentException wrapper for IOException 
	 * because of something else
	 */
	public static String toStringAndReset(InputStream input, int markReadLimit) throws IllegalArgumentException {
		
		if (input != null) {
			
			if(!input.markSupported()) {
				return "unable to dump inputstream. mark is not supported";
			}
			
			input.mark(markReadLimit);
			try {
				return org.apache.commons.io.IOUtils.toString(input);
			}
			catch (IOException e) {
				throw new IllegalArgumentException(": unable to dump content", e);
			}
			finally {				
				try {
					input.reset();
				}
				catch (IOException e) {
					throw new IllegalStateException(e);
				}
			}
		}
		else {
			return null;
		}
	}
	
}
